package top.eggcode.plugins.session.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.eggcode.plugins.session.manager.VerificationSessionManager;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Title:
 * Description: TODO
 * Date: 2021/7/30 23:56
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class ValidationScheduler implements Runnable {

    private static final Logger log = LoggerFactory.getLogger(VerificationSessionManager.class);

    protected boolean enabled = false;

    private long sessionValidationInterval = 60 * 60 * 1000;

    private String threadNamePrefix = "SessionValidationThread-";

    private VerificationSessionManager sessionManager;

    private ScheduledExecutorService service;

    public ValidationScheduler() {
    }

    public ValidationScheduler(VerificationSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    public synchronized void enableSessionValidation() {
        if (this.sessionValidationInterval > 0L) {
            this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
                private final AtomicInteger count = new AtomicInteger(1);

                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setDaemon(true);
                    thread.setName(threadNamePrefix + count.getAndIncrement());
                    return thread;
                }
            });
            this.service.scheduleAtFixedRate(this, sessionValidationInterval,
                    sessionValidationInterval, TimeUnit.MILLISECONDS);
        }
        this.enabled = true;
    }

    public long getSessionValidationInterval() {
        return sessionValidationInterval;
    }

    public void setSessionValidationInterval(long sessionValidationInterval) {
        this.sessionValidationInterval = sessionValidationInterval;
    }

    public String getThreadNamePrefix() {
        return threadNamePrefix;
    }

    public void setThreadNamePrefix(String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public void run() {
        try {
            this.sessionManager.validateSessions();
        } catch (RuntimeException e) {
            log.error("Error while validating the session", e);
            // we don't stop the thread
        }
    }
}
